//
//  WXMoreEmailViewController.m
//  PocketWatchProject
//
//  Created by 黑黑 on 15/11/4.
//  Copyright © 2015年 Atom_Wang. All rights reserved.
//

#import "WXMoreEmailViewController.h"
#import <MessageUI/MessageUI.h>
#import <MessageUI/MFMailComposeViewController.h>
#import "iFLYHandler.h"

@interface WXMoreEmailViewController () <MFMailComposeViewControllerDelegate, UITextViewDelegate, showAlertProtocol>
@property (nonatomic, retain) UITextView *textField;

@property (nonatomic, retain) UIButton *sendBtn;
@property (nonatomic, retain) UIButton *back;
@property (nonatomic, strong) UIButton *voiceBtn;

@property (nonatomic, strong) iFLYHandler *iFLYhander;

@end

@implementation WXMoreEmailViewController

- (iFLYHandler *)iFLYhander {
    if (!_iFLYhander) {
        _iFLYhander = [[iFLYHandler alloc] init];
        _iFLYhander.delegate = self;
    }
    return _iFLYhander;
}

- (void)viewDidLoad {
    [super viewDidLoad];
//    self.view.backgroundColor = [UIColor colorWithRed:0.000 green:0.418 blue:0.673 alpha:1];
    [self.view setBackgroundColor:[UIColor blackColor]];
    // Do any additional setup after loading the view.
    [self creatView];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(resultChange:) name:@"listenResult" object:nil];
    
    self.back = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [self.back setTitle:@"返回" forState: UIControlStateNormal];
    [self.view addSubview:self.back];
    [self.back setFrame:CGRectMake(80, 300, 100, 30)];
    [self.back addTarget:self
                     action:@selector(leftAction)
           forControlEvents:UIControlEventTouchUpInside];
    
    self.sendBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [self.sendBtn setTitle:@"发送" forState:UIControlStateNormal];
    [self.view addSubview:self.sendBtn];
    [self.sendBtn setFrame:CGRectMake(150, 300, 100, 30)];
    [self.sendBtn addTarget:self action:@selector(rightAction) forControlEvents:UIControlEventTouchUpInside];
    
    self.voiceBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [self.voiceBtn setImage:[UIImage imageNamed:@"iconfont-yuyin"] forState:UIControlStateNormal];
    [self.view addSubview:self.voiceBtn];
    [self.voiceBtn setFrame:CGRectMake(250, 300, 100, 30)];
    [self.voiceBtn addTarget:self action:@selector(voiceBtnAction:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)voiceBtnAction:(UIButton *)btn {
    [self startToListening];
}

#pragma mark - 视图将要出现
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    //  初始化语音识别对象
//    [self initRecognizer];
    
    self.navigationController.navigationBarHidden = YES;
    [UIView animateWithDuration:0.5 animations:^{
        NSArray *array = self.tabBarController.view.subviews;
        UIView *view = array[2];
        view.frame = CGRectMake(0, kScreenHeight, kScreenWidth, 49);
        UIView *coverView= array[3];
        coverView.frame = CGRectMake(0, kScreenHeight, kScreenWidth, 49);
    }];
}


#pragma mark - 视图将要消失
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}

- (void)leftAction
{
    [self dismissViewControllerAnimated:YES completion:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"recover" object:nil];
}

- (void)rightAction
{
    [self sendMessage];
}

- (void)creatView
{
    self.textField = [[UITextView alloc] initWithFrame:CGRectMake(5, 25, kScreenWidth - 10, 200)];
    self.textField.text = @"请输入邮件内容(请先激活系统邮箱)";
    self.textField.textColor = [UIColor blackColor];
    self.textField.backgroundColor = [UIColor whiteColor];
    self.textField.delegate = self;
    [self.view addSubview:self.textField];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [UIView animateWithDuration:2.0f animations:^{
            [self.textField setText:@""];
        }];
    });
}

#pragma mark - 新反馈
- (void)sendMessage {
    NSLog(@"发送成功");
    [self sendMailInApp];
    [self displayMailPicker];
}

#pragma mark - 在应用内发送邮件
//激活邮件功能
- (void)sendMailInApp
{
    Class mailClass = (NSClassFromString(@"MFMailComposeViewController"));
    if (!mailClass) {
        [self alertWithMessage:@"当前系统版本不支持应用内发送邮件功能，您可以使用mailto方法代替"];
        return;
    }
    if (![mailClass canSendMail]) {
        [self alertWithMessage:@"用户没有设置邮件账户"];
        return;
    }
    [self displayMailPicker];
}

//调出邮件发送窗口
- (void)displayMailPicker
{
    MFMailComposeViewController *mailPicker = [[MFMailComposeViewController alloc] init];
    
    mailPicker.mailComposeDelegate = self;
    
    //设置主题
    [mailPicker setSubject: @"eMail主题"];
    //添加收件人
    NSArray *toRecipients = [NSArray arrayWithObject: @"1014276604@qq.com"];
    [mailPicker setToRecipients: toRecipients];
    //添加抄送
    NSArray *ccRecipients = [NSArray arrayWithObjects:@"wangxiao@nou.com.cn", nil];
    [mailPicker setCcRecipients:ccRecipients];
    //    //添加密送
    //    NSArray *bccRecipients = [NSArray arrayWithObjects:@"fourth@example.com", nil];
    //    [mailPicker setBccRecipients:bccRecipients];
    
    // 添加一张图片
    UIImage *addPic = [UIImage imageNamed: @"Icon@2x.png"];
    NSData *imageData = UIImagePNGRepresentation(addPic);            // png
    //关于mimeType：http://www.iana.org/assignments/media-types/index.html
    [mailPicker addAttachmentData: imageData mimeType: @"" fileName: @"Icon.png"];
    
    //添加一个pdf附件
    //    NSString *file = [self fullBundlePathFromRelativePath:@"高质量C++编程指南.pdf"];
    //    NSData *pdf = [NSData dataWithContentsOfFile:file];
    //    [mailPicker addAttachmentData: pdf mimeType: @"" fileName: @"高质量C++编程指南.pdf"];
    
    //    NSString *emailBody = @"<font color='red'>eMail</font> 正文";
    NSString *emailBody = self.textField.text;
    [mailPicker setMessageBody:emailBody isHTML:YES];
    [self presentViewController:mailPicker animated:YES completion:nil];
}

#pragma mark - 实现 MFMailComposeViewControllerDelegate
- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"mail.plist"];
    //关闭邮件发送窗口
    [self dismissViewControllerAnimated:YES completion:nil];
    NSString *msg;
    switch (result) {
        case MFMailComposeResultCancelled:
            msg = @"您取消编辑邮件";
            self.textField.text = @"";
            [self.textField.text writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];
            break;
        case MFMailComposeResultSaved:
            msg = @"您成功保存邮件";
            [self.textField.text writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];
            break;
        case MFMailComposeResultSent:
            msg = @"发送成功, 良辰谢谢您的反馈";
            self.textField.text = @"";
            [self.textField.text writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];
            break;
        case MFMailComposeResultFailed:
            msg = @"用户试图保存或者发送邮件失败";
            self.textField.text = @"";
            [self.textField.text writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];
            break;
        default:
            msg = @"";
            self.textField.text = @"";
            [self.textField.text writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];
            break;
    }
    [self alertWithMessage:msg];
}

- (void)alertWithMessage:(NSString *)message {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        // 点击确定按钮执行的代码
        [self.navigationController popViewControllerAnimated:YES];
    }];
    // 给alert添加操作
    [alert addAction:okAction];
    // 模态显示
    [self presentViewController:alert animated:YES completion:nil];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

#pragma mark - 开始
- (void)startToListening {

    [self.iFLYhander startToListening];
}

- (void)resultChange:(NSNotification *)note {
    NSString *str;
    if ([note.userInfo[@"result"] hasPrefix:@"(null)"]) {
        str = [note.userInfo[@"result"] stringByReplacingOccurrencesOfString:@"(null)" withString:@""];
    } else {
        str = note.userInfo[@"result"];
    }
    NSLog(@"❤️❤️❤️❤️❤️%@", note.userInfo[@"result"]);
    NSString *textViewStr = _textField.text;
    _textField.text = @"";
    _textField.text = [NSString stringWithFormat:@"%@%@", textViewStr, str];
}

- (void)showAlert {
    [self presentViewController:self.iFLYhander.alertController animated:YES completion:nil];
}

- (void)removeAlert {
    [self.iFLYhander.alertController dismissViewControllerAnimated:YES completion:nil];
}

@end
